<template>
  <view class="login-page">
    <view class="header">
      <text class="title">手机号登录</text>
      <text class="subtitle">请选择角色并输入验证码完成登录</text>
    </view>

    <view class="form">
      <view class="form-item">
        <text class="label">手机号</text>
        <input
          class="input"
          type="number"
          maxlength="11"
          placeholder="请输入11位手机号"
          v-model="phone"
        />
      </view>

      <view class="form-item code-item">
        <view class="code-input">
          <text class="label">验证码</text>
          <input
            class="input"
            type="number"
            maxlength="6"
            placeholder="请输入验证码"
            v-model="code"
          />
        </view>
        <button class="code-btn" :disabled="countdown > 0 || sending" @click="sendCode">
          {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
        </button>
      </view>

      <view class="form-item">
        <text class="label">选择角色</text>
        <radio-group class="role-group" @change="onRoleChange" :value="selectedRole">
          <label v-for="role in roles" :key="role.value" class="role-option">
            <radio :value="role.value" :checked="role.value === selectedRole" />
            <text class="role-text">{{ role.label }}</text>
          </label>
        </radio-group>
      </view>
    </view>

    <button class="login-btn" :loading="loggingIn" @click="submitLogin">
      登录
    </button>
  </view>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { phoneLogin as apiPhoneLogin } from '@/api/user'
import type { PhoneLoginResp } from '@/api/user'
import type { ApiResponse } from '@/api/request'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

const phone = ref('')
const code = ref('')
const selectedRole = ref('assistant')
const loggingIn = ref(false)
const sending = ref(false)
const countdown = ref(0)
let timer: NodeJS.Timeout | null = null

const roles = [
  { label: '助教', value: 'assistant' },
  { label: '店长', value: 'manager' },
  { label: '加盟商', value: 'franchisee' }
]

const USE_MOCK = true

const roleHomeMap: Record<string, string> = {
  assistant: '/pages/assistant-role/index?tab=city',
  manager: '/pages/manager-role/index?tab=home',
  franchisee: '/pages/franchisee-role/index?tab=home'
}

const applyLogin = (token: string, role: string, phoneNumber: string, name = '用户') => {
  const resolvedRole = role || 'assistant'
  userStore.setUser({ name, token, role: resolvedRole, phone: phoneNumber })
  uni.setStorageSync('token', token)
  uni.setStorageSync('user', { name, role: resolvedRole, phone: phoneNumber })
  uni.showToast({ title: '登录成功', icon: 'none', duration: 1000 })
  setTimeout(() => {
    const target = roleHomeMap[resolvedRole] || '/pages/assistant-role/index?tab=city'
    uni.reLaunch({ url: target })
  }, 400)
}

const mockPhoneLogin = (): Promise<ApiResponse<PhoneLoginResp>> => {
  return Promise.resolve({
    code: 200,
    data: {
      token: `mock-token-${Date.now()}`,
      user: {
        name: `用户${phone.value.slice(-4)}`,
        role: selectedRole.value,
        phone: phone.value
      }
    }
  })
}

const validatePhone = () => /^1[3-9]\d{9}$/.test(phone.value)

const clearTimer = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

const sendCode = () => {
  if (countdown.value > 0 || sending.value) return
  if (!validatePhone()) {
    uni.showToast({ title: '请输入正确手机号', icon: 'none' })
    return
  }
  sending.value = true
  uni.showToast({ title: '验证码已发送', icon: 'none' })
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value -= 1
    if (countdown.value <= 0) clearTimer()
  }, 1000)
  sending.value = false
}

const submitLogin = async () => {
  if (loggingIn.value) return
  // if (!validatePhone()) {
  //   uni.showToast({ title: '请输入正确手机号', icon: 'none' })
  //   return
  // }
  // if (code.value.length === 0) {
  //   uni.showToast({ title: '请输入验证码', icon: 'none' })
  //   return
  // }

  loggingIn.value = true
  try {
    const resp: ApiResponse<PhoneLoginResp> = USE_MOCK
      ? await mockPhoneLogin()
      : await apiPhoneLogin({
          phone: phone.value,
          code: code.value,
          role: selectedRole.value
        })
    if (resp.code === 200) {
      const data = resp.data
      applyLogin(
        data.token,
        data.user?.role || selectedRole.value,
        data.user?.phone || phone.value,
        data.user?.name || `用户${phone.value.slice(-4)}`
      )
    } else {
      uni.showToast({ title: resp.msg || '登录失败', icon: 'none' })
    }
  } catch (error: any) {
    uni.showToast({ title: error?.message || '登录失败', icon: 'none' })
  } finally {
    loggingIn.value = false
  }
}

const onRoleChange = (event: UniApp.RadioGroupChangeEvent) => {
  selectedRole.value = event.detail.value || 'assistant'
}

onUnmounted(() => {
  clearTimer()
})
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  padding: 120rpx 48rpx 80rpx;
  background: linear-gradient(180deg, #f5fffc 0%, #ffffff 100%);
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}

.header {
  margin-bottom: 72rpx;

  .title {
    font-size: 48rpx;
    font-weight: 600;
    color: #222;
  }

  .subtitle {
    display: block;
    margin-top: 16rpx;
    font-size: 26rpx;
    color: #888;
  }
}

.form {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 48rpx 40rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 233, 188, 0.08);
  margin-bottom: 80rpx;
}

.form-item {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  display: block;
  font-size: 28rpx;
  color: #555;
  margin-bottom: 16rpx;
}

.input {
  width: 100%;
  height: 88rpx;
  border-radius: 16rpx;
  background: #f5f7f9;
  padding: 0 24rpx;
  font-size: 30rpx;
  box-sizing: border-box;
}

.code-item {
  display: flex;
  align-items: flex-end;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.code-btn {
  width: 220rpx;
  height: 88rpx;
  border-radius: 16rpx;
  background: linear-gradient(135deg, #00e9bf 0%, #01d4ff 100%);
  color: #fff;
  font-size: 26rpx;
}

.code-btn:disabled {
  background: #d0f7ef;
  color: #8ac6b1;
}

.role-group {
  display: flex;
  gap: 32rpx;
}

.role-option {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.role-text {
  font-size: 28rpx;
  color: #333;
}

.login-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #00e9bf 0%, #00d2ff 100%);
  color: #fff;
  font-size: 32rpx;
  border-radius: 48rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 233, 188, 0.25);
}
</style>
